package com.zjf.fupload.ftp;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPFile;

/**
 * @author zjf
 */
public class FTPClientWrapper {
	
	/**
	 * 服务器
	 */
	private String server;
	private int port = FTPUploader.DEFAULT_PORT;
	/**
	 * 远程路径
	 */
	private String path = "/";
	
	private String username;
	private String password;
	
	/**
	 * 字符编码，默认为中文window下的编码，此处可以防止中文文件名乱码。
	 * TODO: 应该获取系统的编码
	 */
	private String charset = "GBK";
	
	private FTPClient client = new FTPClient();

	public FTPClientWrapper(String server, int port, String path, String username, String password) {
		this.server = server;
		this.port = port;
		this.path = path;
		this.username = username;
		this.password = password;
	} 
	
	public void login() throws Exception {
		client.setType(FTPClient.TYPE_BINARY);
		client.setCharset(charset);
    	client.connect(server, port);
    	client.login(username, password);
    	client.changeDirectory(path);
	}
	
	public FTPFileInfo[] list() throws Exception {
    	FTPFile[] ftpFiles = client.list();
    	
    	if(ftpFiles == null || ftpFiles.length <= 0) {
    		return new FTPFileInfo[]{};
    	}
    	
    	FTPFileInfo[] infos = new FTPFileInfo[ftpFiles.length];
    	
    	for(int i=0; i<ftpFiles.length; i++) {
    		FTPFile file = ftpFiles[i];
    		infos[i] = new FTPFileInfo();
    		infos[i].setLink(file.getLink());
    		infos[i].setName(file.getName());
    		infos[i].setModifiedDate(file.getModifiedDate());
    		infos[i].setSize(file.getSize());
    		infos[i].setType(file.getType());
    	}
    	
    	return infos;
    	
	}
	
	public void changeDirectory(String dirctory) throws Exception {
		client.changeDirectory(dirctory);
	}
	
	public void changeDirectoryUp() throws Exception {
		client.changeDirectoryUp();
	}
	
	public String currentDirectory() throws Exception {
		return client.currentDirectory();
	}
	
	public void disconnect(boolean sendQuitCommand) throws Exception {
		client.disconnect(sendQuitCommand);
	}
	
	public void delete(String fileName) throws Exception {
		client.deleteFile(fileName);
	}
	
	public void deleteDirectory(String path) throws Exception {
		client.deleteDirectory(path);
	}
	
}
